/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 */
package org.nanhill.vest.component;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 * 
 */
public class DefaultBuilder implements Builder {
	List<Object> buffers = new ArrayList<Object>(128);

	public List<Object> getBuffers() {
		return buffers;
	}

	public void append(Dynamic dynamic) {
		buffers.add(dynamic);
	}

	public void append(String str) {
		StringBuilder builder = null;
		if (buffers.isEmpty()) {
			builder = new StringBuilder();
			buffers.add(builder);
		} else {
			Object buf = buffers.get(buffers.size() - 1);
			if (buf instanceof StringBuilder) {
				builder = (StringBuilder) buf;
			} else {
				builder = new StringBuilder();
				buffers.add(builder);
			}
		}
		builder.append(str);
	}

	/**
	 * Performance Optimize
	 * 
	 * StringBuilder buffers --> String buffers
	 */
	public void shrink() {
		for (int i = 0; i < buffers.size(); i++) {
			Object obj = buffers.get(i);
			if (obj instanceof StringBuilder) {
				buffers.remove(i);
				StringBuilder sb = (StringBuilder) obj;
				buffers.add(i, sb.toString());
			}
		}

	}

}
